<template>
  <el-dialog
    title="订单历史"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="800px"
    top="5vh"
    destroy-on-close
  >
    <div class="order-history">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单号/客户"
          prefix-icon="fa fa-search"
          clearable
          @input="handleSearch"
        ></el-input>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          @change="handleSearch"
        ></el-date-picker>
        
        <el-select
          v-model="statusFilter"
          placeholder="订单状态"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      
      <el-table
        :data="filteredOrders"
        stripe
        border
        height="400px"
        v-loading="loading"
      >
        <el-table-column label="订单号" prop="orderNo" width="120"></el-table-column>
        <el-table-column label="时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="客户" prop="customerName" width="120"></el-table-column>
        <el-table-column label="商品数" prop="itemCount" width="80" align="center"></el-table-column>
        <el-table-column label="订单金额" width="120" align="right">
          <template #default="scope">
            ¥{{ formatPrice(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="paymentMethod" width="100"></el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="viewOrderDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="loadOrder(scope.row.orderNo)"
              :disabled="scope.row.status !== 'pending'"
            >
              载入
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalOrders"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-header">
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单号:</span>
              <span class="value">{{ selectedOrder.orderNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">日期:</span>
              <span class="value">{{ formatDate(selectedOrder.createTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态:</span>
              <el-tag :type="getStatusType(selectedOrder.status)">
                {{ getStatusText(selectedOrder.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="customer-info">
            <div class="info-item">
              <span class="label">客户:</span>
              <span class="value">{{ selectedOrder.customerName }}</span>
            </div>
            <div class="info-item">
              <span class="label">电话:</span>
              <span class="value">{{ selectedOrder.customerPhone }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-items">
          <h4 class="section-title">订单明细</h4>
          <el-table
            :data="selectedOrder.items"
            stripe
            border
          >
            <el-table-column label="商品名称" prop="name"></el-table-column>
            <el-table-column label="单价" width="100" align="right">
              <template #default="scope">
                ¥{{ formatPrice(scope.row.price) }}
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="80" align="center"></el-table-column>
            <el-table-column label="小计" width="120" align="right">
              <template #default="scope">
                ¥{{ formatPrice(scope.row.price * scope.row.quantity) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="detail-summary">
          <div class="summary-row">
            <span class="label">商品总额:</span>
            <span class="value">¥{{ formatPrice(selectedOrder.totalAmount) }}</span>
          </div>
          <div class="summary-row" v-if="selectedOrder.discountAmount > 0">
            <span class="label">折扣金额:</span>
            <span class="value discount">-¥{{ formatPrice(selectedOrder.discountAmount) }}</span>
          </div>
          <div class="summary-row total">
            <span class="label">实付金额:</span>
            <span class="value">¥{{ formatPrice(selectedOrder.paidAmount) }}</span>
          </div>
          <div class="summary-row">
            <span class="label">支付方式:</span>
            <span class="value">{{ selectedOrder.paymentMethod }}</span>
          </div>
        </div>
        
        <div class="detail-footer">
          <el-button
            type="primary"
            plain
            @click="printOrderDetail"
          >
            <i class="fa fa-print"></i> 打印小票
          </el-button>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 订单类型定义
interface OrderItem {
  id: number;
  name: string;
  price: number;
  quantity: number;
}

interface Order {
  id: number;
  orderNo: string;
  createTime: string;
  customerName: string;
  customerPhone: string;
  itemCount: number;
  totalAmount: number;
  paidAmount: number;
  discountAmount: number;
  paymentMethod: string;
  status: string;
  items: OrderItem[];
}

// 示例数据
const mockOrders = [
  {
    id: 1,
    orderNo: 'POS20230327001',
    createTime: '2023-03-27 15:30:22',
    customerName: '张三',
    customerPhone: '13800138001',
    itemCount: 3,
    totalAmount: 599,
    paidAmount: 599,
    discountAmount: 0,
    paymentMethod: '微信支付',
    status: 'completed',
    items: [
      { id: 1, name: '办公椅', price: 299, quantity: 1 },
      { id: 2, name: '签字笔(10支装)', price: 25, quantity: 2 },
      { id: 3, name: 'A4纸(500张)', price: 39, quantity: 5 }
    ]
  },
  {
    id: 2,
    orderNo: 'POS20230327002',
    createTime: '2023-03-27 16:45:10',
    customerName: '李四',
    customerPhone: '13900139002',
    itemCount: 2,
    totalAmount: 5298,
    paidAmount: 4768,
    discountAmount: 530,
    paymentMethod: '支付宝',
    status: 'completed',
    items: [
      { id: 1, name: '笔记本电脑', price: 4999, quantity: 1 },
      { id: 2, name: '鼠标', price: 299, quantity: 1 }
    ]
  },
  {
    id: 3,
    orderNo: 'POS20230327003',
    createTime: '2023-03-27 17:20:05',
    customerName: '王五',
    customerPhone: '13700137003',
    itemCount: 1,
    totalAmount: 1299,
    paidAmount: 1299,
    discountAmount: 0,
    paymentMethod: '银行卡',
    status: 'completed',
    items: [
      { id: 1, name: '打印机', price: 1299, quantity: 1 }
    ]
  },
  {
    id: 4,
    orderNo: 'POS20230328001',
    createTime: '2023-03-28 09:15:38',
    customerName: '赵六',
    customerPhone: '13600136004',
    itemCount: 4,
    totalAmount: 783,
    paidAmount: 705,
    discountAmount: 78,
    paymentMethod: '现金',
    status: 'completed',
    items: [
      { id: 1, name: '办公桌', price: 699, quantity: 1 },
      { id: 2, name: '矿泉水', price: 3, quantity: 10 },
      { id: 3, name: '咖啡', price: 15, quantity: 2 },
      { id: 4, name: '洗手液', price: 29, quantity: 1 }
    ]
  },
  {
    id: 5,
    orderNo: 'POS20230328002',
    createTime: '2023-03-28 14:50:20',
    customerName: '孙七',
    customerPhone: '13500135005',
    itemCount: 2,
    totalAmount: 2500,
    paidAmount: 0,
    discountAmount: 0,
    paymentMethod: '待付款',
    status: 'pending',
    items: [
      { id: 1, name: '投影仪', price: 2999, quantity: 1 },
      { id: 2, name: '文件柜', price: 499, quantity: 1 }
    ]
  }
]

export default defineComponent({
  name: 'OrderHistoryDialog',
  props: {
    modelValue: {
      type: Boolean,
      required: true
    }
  },
  emits: ['update:modelValue', 'select-order'],
  setup(props, { emit }) {
    // 状态变量
    const loading = ref(false)
    const searchQuery = ref('')
    const dateRange = ref<[Date, Date] | null>(null)
    const statusFilter = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const detailDialogVisible = ref(false)
    const selectedOrder = ref<Order | null>(null)
    
    // 订单列表
    const orders = ref<Order[]>(mockOrders)
    
    // 状态选项
    const statusOptions = [
      { value: 'completed', label: '已完成' },
      { value: 'pending', label: '待付款' },
      { value: 'cancelled', label: '已取消' }
    ]
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '今天',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setHours(0, 0, 0, 0)
          return [start, end]
        }
      },
      {
        text: '昨天',
        value: () => {
          const end = new Date()
          end.setHours(23, 59, 59, 999)
          end.setTime(end.getTime() - 3600 * 1000 * 24)
          const start = new Date()
          start.setHours(0, 0, 0, 0)
          start.setTime(start.getTime() - 3600 * 1000 * 24)
          return [start, end]
        }
      },
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        }
      },
      {
        text: '本月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setDate(1)
          start.setHours(0, 0, 0, 0)
          return [start, end]
        }
      }
    ]
    
    // 计算属性：过滤后的订单列表
    const filteredOrders = computed(() => {
      let result = orders.value
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(
          order => 
            order.orderNo.toLowerCase().includes(query) || 
            order.customerName.toLowerCase().includes(query)
        )
      }
      
      // 日期过滤
      if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
        const startDate = dateRange.value[0].getTime()
        const endDate = dateRange.value[1].getTime()
        
        result = result.filter(order => {
          const orderDate = new Date(order.createTime).getTime()
          return orderDate >= startDate && orderDate <= endDate
        })
      }
      
      // 状态过滤
      if (statusFilter.value) {
        result = result.filter(order => order.status === statusFilter.value)
      }
      
      return result.slice(
        (currentPage.value - 1) * pageSize.value,
        currentPage.value * pageSize.value
      )
    })
    
    // 计算属性：订单总数
    const totalOrders = computed(() => {
      return orders.value.length
    })
    
    // 格式化价格
    const formatPrice = (price: number) => {
      return price.toFixed(2)
    }
    
    // 格式化日期
    const formatDate = (dateString: string) => {
      return new Date(dateString).toLocaleString()
    }
    
    // 获取状态类型样式
    const getStatusType = (status: string): 'success' | 'warning' | 'info' | 'danger' => {
      const statusMap: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
        completed: 'success',
        pending: 'warning',
        cancelled: 'danger'
      }
      
      return statusMap[status] || 'info'
    }
    
    // 获取状态显示文本
    const getStatusText = (status: string) => {
      const statusMap: Record<string, string> = {
        completed: '已完成',
        pending: '待付款',
        cancelled: '已取消'
      }
      
      return statusMap[status] || '未知'
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    // 处理页码变化
    const handleCurrentChange = (page: number) => {
      currentPage.value = page
    }
    
    // 处理每页显示数量变化
    const handleSizeChange = (size: number) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    // 查看订单详情
    const viewOrderDetail = (order: Order) => {
      selectedOrder.value = order
      detailDialogVisible.value = true
    }
    
    // 加载订单到购物车
    const loadOrder = (orderNo: string) => {
      emit('select-order', orderNo)
      emit('update:modelValue', false)
      ElMessage.success(`已加载订单: ${orderNo}`)
    }
    
    // 打印订单详情
    const printOrderDetail = () => {
      if (!selectedOrder.value) return
      
      console.log('打印订单详情:', selectedOrder.value.orderNo)
      ElMessage.success('订单打印中...')
    }
    
    // 组件挂载时获取订单数据
    onMounted(() => {
      loading.value = true
      
      // 模拟API请求
      setTimeout(() => {
        // 实际应用中从后端获取订单数据
        loading.value = false
      }, 500)
    })
    
    return {
      loading,
      searchQuery,
      dateRange,
      statusFilter,
      statusOptions,
      dateShortcuts,
      currentPage,
      pageSize,
      detailDialogVisible,
      selectedOrder,
      filteredOrders,
      totalOrders,
      formatPrice,
      formatDate,
      getStatusType,
      getStatusText,
      handleSearch,
      handleCurrentChange,
      handleSizeChange,
      viewOrderDetail,
      loadOrder,
      printOrderDetail
    }
  }
})
</script>

<style scoped lang="scss">
.order-history {
  .search-bar {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    
    .el-input {
      flex: 1;
    }
    
    .el-date-picker {
      width: 300px;
    }
    
    .el-select {
      width: 120px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.order-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    
    .order-info, .customer-info {
      .info-item {
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        
        .label {
          color: #606266;
          margin-right: 10px;
          min-width: 60px;
        }
        
        .value {
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }
  
  .detail-items {
    margin-bottom: 20px;
    
    .section-title {
      margin-bottom: 10px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .detail-summary {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    .summary-row {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        color: #606266;
        margin-right: 10px;
      }
      
      .value {
        color: #303133;
        min-width: 120px;
        text-align: right;
        
        &.discount {
          color: #f56c6c;
        }
      }
      
      &.total {
        font-size: 16px;
        font-weight: 500;
        margin-top: 5px;
        padding-top: 5px;
        border-top: 1px dashed #dcdfe6;
        
        .label, .value {
          color: #f56c6c;
        }
      }
    }
  }
  
  .detail-footer {
    display: flex;
    justify-content: center;
  }
}
</style> 